<template>
  <div>
    <el-card shadow="always">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="用户名 :" class="el-form-item-custom">
          <el-input v-model="formInline.name" placeholder="用户名" size="small"></el-input>
        </el-form-item>
        <el-form-item label="时间 :" class="el-form-item-custom">
          <el-date-picker
            v-model="dateValue"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
        </el-form-item>
        <el-form-item class="el-form-item-custom">
          <el-button type="text" @click="handleClick(formInline,'search')" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <hyl-table :tableData="tableData" :columns="columns" :specialColumns="specialColumns" v-on:tableSelection="tableSelection">
      <template slot="buttons">
        <el-button type="text" icon="el-icon-edit" v-if="buttonsVisible.editVisible" @click="handleClick({},'edit')">编辑</el-button>
        <el-button type="text" icon="el-icon-circle-plus-outline" v-if="buttonsVisible.addVisible" @click="handleClick({},'add')">添加</el-button>
        <el-button type="text" icon="el-icon-delete" v-if="buttonsVisible.deleteVisible" @click="handleClick({},'delete')">删除</el-button>
        <el-button type="text" icon="el-icon-setting" v-if="buttonsVisible.grantVisible" @click="handleClick({},'grant')">授权</el-button>
      </template>
      <!-- 定制表格单元格所显示内容 -->
      <div slot="createDateTime" slot-scope="scope">{{scope.$row.createDateTime | dateString}}</div>
      <div slot="modifyDateTime" slot-scope="scope">{{scope.$row.modifyDateTime | dateString}}</div>
    </hyl-table>
    <hyl-pagination v-on:fetch="fetch" :total="total" :page-sizes="[5,10,15]"
                    :page-size="5"/>
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="40%">
      <el-form  label-width="80px" :model="rowData">
        <el-form-item label="用户">
          <el-input v-model="rowData.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="rowData.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('edit')">取 消</el-button>
        <el-button type="primary" @click="handleOk(rowData,'edit')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加"  :visible.sync="addDialogVisible" ref="addForm" width="40%">
      <el-form  label-width="80px" :model="addData">
        <el-form-item label="用户">
          <el-input v-model="addData.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addData.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('add')">取 消</el-button>
        <el-button type="primary" @click="handleOk(addData,'add')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="用户授权" :visible="grantDialogVisible" width="40%">
      <el-input v-model="filterText" placeholder="请输入关键字过滤" size="small"></el-input>
      <el-button type="text" @click="handleOk({},'grant')"><i class="fa fa-cog fa-fw"></i>&nbsp;授权</el-button>
      <el-button type="text" @click="handleCancel('grant')"><i class="fa fa-remove fa-fw"></i>&nbsp;取消</el-button>
      <el-tree
        :data="treeData"
        node-key="id"
        :props="defaultProps"
        :filter-node-method="filterNode"
        :show-checkbox="true"
        ref="tree"></el-tree>
    </el-dialog>
  </div>
</template>
<script>
import hylTable from '@/components/table'
import {fetch, del, put, post} from '@/utils/http'
import {mapGetters} from 'vuex'
import axios from 'axios'
import hylPagination from '@/components/pagination'
import moment from 'moment'
export default {
  name: 'User',
  components: {
    hylTable,
    hylPagination
  },
  data () {
    return {
      tableData: [],
      specialColumns: [{
        type: 'selection',
        width: '55'
      }, {
        type: 'index',
        indexMethod: this.indexMethod
      }],
      columns: [{
        prop: 'createDateTime',
        label: '日期',
        width: '240'
      }, {
        prop: 'name',
        label: '姓名',
        width: '180'
      }, {
        prop: 'password',
        label: '密码',
        width: '120'
      }, {
        fixed: '',
        prop: 'modifyDateTime',
        label: '修改时间',
        width: '240'
      }],
      page: 1,
      limit: 5,
      total: 0,
      editDialogVisible: false,
      addDialogVisible: false,
      grantDialogVisible: false,
      buttonsVisible: {
        addVisible: true,
        editVisible: true,
        deleteVisible: true,
        grantVisible: true
      },
      multipleSelection: [],
      rowData: {},
      addData: {
        name: '',
        password: ''
      },
      dateValue: [],
      formInline: {
        name: '',
        region: '',
        createDateTimeStart: '',
        createDatetimeEnd: ''
      },
      treeData: [],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    filterText (value) {
      this.$refs.tree.filter(value)
    }
  },
  computed: {
    ...mapGetters(['resources'])
  },
  methods: {
    filterNode (value, data) {
      // 当value为空时,那么所有的都为true
      if (!value) return true
      /// 下标>0 为true,否则为false
      return data.label.indexOf(value) !== -1
    },
    tableSelection (val) {
      this.multipleSelection = val
    },
    indexMethod (index) {
      return index + 1 + (this.page - 1) * this.limit
    },
    handleClick (row = {}, type = '') {
      switch (type) {
        case 'add':
          this.addDialogVisible = true
          this.$refs['addForm'].resetFields()
          break
        case 'delete':
          if (this.multipleSelection.length > 0) {
            let ids = ''
            let usernames = ''
            this.multipleSelection.forEach((selection) => {
              ids = ids + selection.id + ','
              usernames = usernames + selection.name + ','
            })
            this.$confirm(usernames + '确定要删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              del('long-base-upms/sysUser/deleteBatch', {params: {ids: ids.slice(0, ids.length - 1)}}).then((res) => {
                this.$message.success('删除成功!')
                this.fetch()
              })
            })
          } else {
            this.$confirm('此操作需要至少选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'edit':
          if (this.multipleSelection.length === 1) {
            this.rowData = this.multipleSelection[0]
            this.editDialogVisible = true
          } else {
            this.$confirm('此操作只能选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'search':
          console.log(this.dateValue)
          if (this.dateValue && this.dateValue.length > 0) {
            row.createDateTimeStart = moment(this.dateValue[0]).isValid() ? moment(this.dateValue[0]).format('YYYY-MM-DD HH:mm:ss') : undefined
            row.createDatetimeEnd = moment(this.dateValue[1]).isValid() ? moment(this.dateValue[1]).format('YYYY-MM-DD HH:mm:ss') : undefined
          }
          let page = {
            page: 1,
            limit: 5
          }
          Object.assign(page, row)
          this.fetch(page)
          // 对formLine作清空操作
          for (let item in this.formInline) {
            this.formInline[item] = ''
          }
          break
        case 'grant':
          /// 1.判断是否选中了一行,如果不符合条件,直接提示
          if (this.multipleSelection.length === 1) {
            /// 2.弹出用户角色授权对话框
            this.grantDialogVisible = true
            /// 3.从服务器端获取数据
            let _this = this
            axios.all([
              fetch('long-base-upms/sysUser/loadRolesByUserId', {
                id: this.multipleSelection[0].id
              }), fetch('long-base-upms/sysUser//loadAllRolesTreeNode')
            ]).then(axios.spread(function (roleByUserId, all) {
              _this.treeData = all.data.treeNodeList ? all.data.treeNodeList : []
              let ids = []
              let temp = roleByUserId.data.treeNodeList ? roleByUserId.data.treeNodeList : []
              temp.forEach((item) => {
                ids.push(item.id)
              })
              _this.$refs.tree.setCheckedKeys(ids)
            }))
          } else {
            /// 不符合条件提示信息
            this.$message('请选择一行!')
          }
          break
        default:
          alert('其它操作')
      }
    },
    handleOk (row, type) {
      switch (type) {
        case 'edit':
          put('long-base-upms/sysUser/update', row).then((res) => {
            const h = this.$createElement
            this.$message({
              message: h('p', null, [
                h('i', { style: 'color: teal' }, '更新成功!')
              ])
            })
            this.editDialogVisible = false
          })
          break
        case 'add':
          post('long-base-upms/sysUser/add', row).then((res) => {
            this.$message.success('添加用户成功!')
            this.addDialogVisible = false
            this.fetch()
          })
          break
        case 'grant':
          // 1.获取 userId与roleIds
          let userId = this.multipleSelection[0].id
          let roleIds = this.$refs.tree.getCheckedKeys().join(',')
          // 2.向服务器端提交数据
          post('long-base-upms/sysUser/grantRole', {
            id: userId,
            roleIds: roleIds
          }).then((res) => {
            if (res.status === 200) {
              this.grantDialogVisible = false
            } else {
            }
            this.$message(res.message)
          })
          break
        default:
          break
      }
    },
    handleCancel (type) {
      if (type === 'edit') {
        this.editDialogVisible = false
      } else if (type === 'add') {
        this.addDialogVisible = false
      } else if (type === 'grant') {
        this.grantDialogVisible = false
      }
    },
    fetch (page = {
      page: 1,
      limit: 5
    }) {
      fetch('long-base-upms/sysUser/page', page).then((res) => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.page = page.page
        this.limit = page.limit
      })
    }
  },
  mounted: function () {
    this.fetch()
    // 在判断之前进行 隐藏
    for (let i in this.buttonsVisible) {
      this.buttonsVisible[i] = false
    }
    // 根据当前用户所拥有的权限来判断哪些应显示
    let filter = this.resources.filter((item) => {
      if (item.type === 0) {
        return true
      } else {
        return false
      }
    })
    // console.log(this.$route.path)
    filter.forEach((item) => {
      // console.log(item.url + ':' + (this.$route.path + '/add'))
      if (item.url === (this.$route.path + '/add')) {
        this.buttonsVisible.addVisible = true
      }

      if (item.url === (this.$route.path + '/edit')) {
        this.buttonsVisible.editVisible = true
      }

      if (item.url === (this.$route.path + '/delete')) {
        this.buttonsVisible.deleteVisible = true
      }

      if (item.url === (this.$route.path + '/grant')) {
        this.buttonsVisible.grantVisible = true
      }
    })
  }
}
</script>
<style scoped>
</style>
